package ks.client.controllers.requests;

import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import ks.client.UserContext;
import ks.client.gui.UMGUI3;
import ks.client.lobby.Lobby;
import ks.framework.common.Message;
import ks.framework.interfaces.IProcessMessage;
import ks.managers.user.User;
import ks.managers.user.UserManager;

/**
 * The controller for the disconnecting request.
 * 
 * @author Christopher Page
 * @author Samir Zutshi
 */
public class DisconnectingController implements IProcessMessage{
	Lobby lobby;
	
	public DisconnectingController(Lobby lobby){
		this.lobby = lobby;
		System.out.println("YOU HAVE ACCESSED THE DISCONNECTING_CONTROLLER");

	}
	/**
	 * Client has received disconnecting message. Process it.
     * 
	 * @param m The message to process.
	 * @return true on success; false on failure.
	 */
	public boolean process(Message m) {
		// Get our context
		UserContext context = lobby.getUserContext();
		
		// Fit into existing set of users.
		UserManager uman = context.getUserManager();
		
		// and update on our GUI
		UMGUI3 gui = lobby.getUMGUI3();
		
		
		// extract information from the message
		Node disconnecting = m.contents();
		
		NodeList playernamesList = disconnecting.getChildNodes();
		Node playername, nameTmp;
		NamedNodeMap nnpTmp;
		User uTmp;
		
		System.out.println("About to go through playernameslist");
		
		for (int i = 0; i < playernamesList.getLength(); i++) {
			playername = playernamesList.item(i);
			
			// if playername does not exist, continue to next loop iteration
			if (playername == null)
				continue;
			
			// if playername is not a playername element, continue to next loop iteration
			if (!playername.getNodeName().equalsIgnoreCase("playername"))
				continue;
			
			nnpTmp = playername.getAttributes();
			
			nameTmp = nnpTmp.getNamedItem("name");
			
			// if no name provided, continue to next loop iteration
			if (nameTmp == null)
				continue;
			
			uTmp = new User (nameTmp.getNodeValue(), "");
			
			uman.removeUser(uTmp);
			
			System.out.println("about to remove user.... please hold...");
			
			gui.removeUser(uTmp);
			gui.refreshTable();
		}
		
		return true;
	}
}
